package com.mycjj.android.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class BitmapUtils {	
	public static Bitmap getBitmap(InputStream in) {
		return BitmapFactory.decodeStream(in);
	}

	public static  Bitmap getBitmap(byte[] data, int scale) {
		Options opts = new Options();
		opts.inSampleSize = scale;
		return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
	}
	

	public static Bitmap getBitmap(byte[] data, int width, int height) {
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		int x = opts.outWidth / width;
		int y = opts.outHeight / height;
		int scale = x > y ? x : y;
		return getBitmap(data, scale);
	}
	
	public static Bitmap getBitmap(String path){
		return BitmapFactory.decodeFile(path);
	}
	
	/**
	 *该方法是将｛@link Drawable} 对象转换成｛@link Bitmap} 对象
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		if(drawable == null){
			return null;
		}
		Bitmap bitmap = Bitmap.createBitmap(
				drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(), 
				drawable.getOpacity() != PixelFormat.OPAQUE ?
						Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  
		if(bitmap == null){
			return null;
		}
		Canvas canvas = new Canvas(bitmap);  
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
		drawable.draw(canvas);  
		return bitmap;  
	} 
	
	public static String save(Context context, Drawable drawable, String picName){
		Bitmap bitmap = drawableToBitmap(drawable);
		
		Log.i("info", "======="+Environment.
				getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
		
		Log.i("info", "====getExternalStorageDirectory="+Environment.
				getExternalStorageDirectory().getPath());
		
		File file = new File(Environment.getExternalStorageDirectory() + "/SonyStore/" + File.separator + picName);
//		File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/SonyStore/" + File.separator + picName);
		try {
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			if(!file.exists())
				file.createNewFile();
			
			FileOutputStream out = new FileOutputStream(file);
			bitmap.compress(CompressFormat.PNG, 100, out);
			try {
				out.flush();
			} catch (IOException e) {
                e.printStackTrace();
			}
			try {
				out.close();
			} catch (IOException e) {
                e.printStackTrace();
			}
			//这里刷新有点慢.....
			//context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()+"/SonyStore")));
			MediaScannerConnection.scanFile(context,
			            new String[] { file.toString() }, null,
			            new MediaScannerConnection.OnScanCompletedListener() {
			        public void onScanCompleted(String path, Uri uri) {
			            Log.i("ExternalStorage", "Scanned " + path + ":");
			            Log.i("ExternalStorage", "-> uri=" + uri);
			        }
			    });
			
			Log.i("info", "====file.getAbsolutePath()="+file.getAbsolutePath());
			return file.getAbsolutePath();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
		
	}
	
	public static void saveLocateImage(Context context,Bitmap bitmap,String picName){
		String filename = context.getFilesDir().toString()+"/images/"+picName.replace("/", "_");
		File file = new File(filename);
		try {
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			if(!file.exists())
				file.createNewFile();
			FileOutputStream out = new FileOutputStream(filename);
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			try {
				out.flush();
			} catch (IOException e) {
                e.printStackTrace();
			}
			try {
				out.close();
			} catch (IOException e) {
                e.printStackTrace();
			}
		} catch (Exception e) {
		  e.printStackTrace();
		}
	}
	
	public static Bitmap readLocateImage(Context context,String picName){
		String filename = context.getFilesDir().toString()+"/images/"+picName.replace("/", "_");
		File file = new File(filename);
		if(file.exists()){
		    Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath());
		    return b;
		}else{
			return null;
		}
	}
}
